<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/17
 * Time: 上午10:09
 */

namespace app\merchant\controller;

use app\common\controller\AdminBase;
use app\common\controller\Helpinfo;
use app\common\model\Agent;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\System;
use app\common\model\WxchMenu;
use app\common\model\WxOpen;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Wxsystem extends AdminBase
{

    //自定义菜单
    public function wx_menu()
    {
        $WxchMenu = new WxchMenu();
        $Momerchant = new Momerchant();
        $top_mid = Session::get('login_top_mid');
        $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');
        $map['wx_open_id'] = $wx_open_id;
        $is_menu = $WxchMenu->where($map)->find();
        if (Request()->isAjax()) {
            $arr = request()->post();
            if (isset($arr['menu'])){
                $datas['is_new'] = 1;
                $datas['menu_data'] = json_encode($arr['menu'],JSON_UNESCAPED_UNICODE);
            }else{
                $datas = $arr;
            }
            if ($is_menu) {
                $WxchMenu->save($datas, ['wx_open_id' => $wx_open_id]);
            } else {
                $datas['wx_open_id'] = $wx_open_id;
                $WxchMenu->save($datas);
            }
            $data['wx_open_id'] = $wx_open_id;
            $res = $this->tj_menu($arr['menu']);
            if ($res['errcode'] == 0) {
                $rarr['code'] = 0;
                $rarr['message'] = 'success';
                $rarr['data'] = '';
            } else {
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
                $rarr['code'] = $res['errcode'];
                $rarr['message'] = $errmsg;
                $rarr['data'] = '';
            }
            return json($rarr);
        } else {
            $map['wx_open_id'] = $wx_open_id;
            $is_menu = $WxchMenu->where($map)->find();
            if ($is_menu) {
                $menu = $is_menu;
            } else {
                $menu = $WxchMenu->where($map)->find();
            }
            $momach = $Momerchant->where('id', $top_mid)->find();
            $this->assign('data', $menu);
            $this->assign('momach', $momach);
            return $this->fetch();
        }
    }

    //获取
    public function getwxmenu(){
//        if (Request()->isAjax()){
        $arr = request()->post();
        $WxchMenu = new WxchMenu();
        $Momerchant = new Momerchant();
        $top_mid = Session::get('login_top_mid');
        $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');
        $map['wx_open_id'] = $wx_open_id;
        $menu = $WxchMenu->where($map)->find();
        if ($menu){
            if ($menu['is_new'] == 1){
                $data = json_decode($menu['menu_data'],true);
            }else{
                $data = $this->create_menu($map);
            }

            $res['code'] = 0;
            $res['message'] = 'success';
            $res['data']['menu'] = $data;

        }else{
            $res['code'] = 9001;
            $res['message'] = 'error';
            $res['data'] = '';
        }
        return $res;
//        }
    }

    //生成自定义菜单
    public function create_menu($arr)
    {
        header("Content-Type: text/html;charset=utf-8");
        $menu = new WxchMenu();
        $map['wx_open_id'] = $arr['wx_open_id'];
        $sj = $menu->where($map)->find();
        for ($i = 1; $i <= 5; $i++) {
            if ($sj['first1_' . $i . '_type'] == "view") {
                $s = 'url';
            } elseif ($sj['first1_' . $i . '_type'] == "click") {
                $s = 'key';
            }
            if (!empty($sj['first1_' . $i . ''])) {
                $arr1[] = array('type' => $sj['first1_' . $i . '_type'], 'name' => urldecode(urlencode($sj['first1_' . $i . ''])), $s => urlencode($sj['first1_' . $i . '_value']));
            }

        }
        for ($i = 1; $i <= 5; $i++) {
            if ($sj['second1_' . $i . '_type'] == "view") {
                $s = 'url';
            } elseif ($sj['second1_' . $i . '_type'] == "click") {
                $s = 'key';
            }
            if (!empty($sj['second1_' . $i . ''])) {
                $arr2[] = array('type' => $sj['second1_' . $i . '_type'], 'name' => urlencode($sj['second1_' . $i . '']), $s => urlencode($sj['second1_' . $i . '_value']));
            }
        }
        for ($i = 1; $i <= 5; $i++) {
            if ($sj['third1_' . $i . '_type'] == "view") {
                $s = 'url';
            } elseif ($sj['third1_' . $i . '_type'] == "click") {
                $s = 'key';
            }
            if (!empty($sj['third1_' . $i . ''])) {
                $arr3[] = array('type' => $sj['third1_' . $i . '_type'], 'name' => urlencode($sj['third1_' . $i . '']), $s => urlencode($sj['third1_' . $i . '_value']));
            }
        }
        if (!empty($sj['first'])) {
            if ($sj['first_type'] == "view") {
                $s = 'url';

            } elseif ($sj['first_type'] == "click") {
                $s = 'key';
            }
            if (empty($sj['first_value'])) {
                $sarr1 = array('name' => urlencode($sj['first']), 'sub_button' => $arr1);
            } else {
                $sarr1 = array('type' => $sj['first_type'], 'name' => urlencode($sj['first']), $s => urlencode($sj['first_value']));
            }
        } else {
            unset($sarr1);
            $sarr1 = [];
        }
        if (!empty($sj['second'])) {
            if ($sj['second_type'] == "view") {
                $s = 'url';
            } elseif ($sj['second_type'] == "click") {
                $s = 'key';
            }
            if (empty($sj['second_value'])) {
                $sarr2 = array('name' => urlencode($sj['second']), 'sub_button' => $arr2);
            } else {
                $sarr2 = array('type' => $sj['second_type'], 'name' => urlencode($sj['second']), $s => urlencode($sj['second_value']));
            }
        } else {
            unset($sarr2);
            $sarr2 = [];
        }
        if (!empty($sj['third'])) {
            if ($sj['third_type'] == "view") {
                $s = 'url';
            } elseif ($sj['third_type'] == "click") {
                $s = 'key';
            }
            if (empty($sj['third_value'])) {
                $sarr3 = array('name' => urlencode($sj['third']), 'sub_button' => $arr3);
            } else {
                $sarr3 = array('type' => $sj['third_type'], 'name' => urlencode($sj['third']), $s => urlencode($sj['third_value']));
            }
        } else {
            unset($sarr3);
            $sarr3 = [];
        }
        $aarr = array($sarr1, $sarr2, $sarr3);
        $darr = array_filter($aarr);
        $arr = array('button' => $darr);
        $menu = urldecode(json_encode($arr,JSON_UNESCAPED_UNICODE));
        return $menu;
    }

    public function tj_menu($menu)
    {

        $options = $this->options();
        $wxObj = new Wxobjopen($options);
        $s = $wxObj->createMenu($menu);
        return $s;
    }

    //获取自定义菜单设置
    public function get_menuset(){
        $options = $this->options();
        $wxObj = new Wxobjopen($options);
        $menuinfo = $wxObj->getMenu();
        $data['code'] = 0;
        $data['message'] = 'success';
        $data['data'] = $menuinfo;
        return json($data);
    }

    //获取所属行业
    public function get_industry()
    {
        $option = $this->options();
        $wxObj = new Wxobjopen($option);
        $res = $wxObj->getTMIndustry();

    }

    //获取模板列表
    public function gettpllist()
    {
        $option = $this->options();
        $wxObj = new Wxobjopen($option);
        $res = $wxObj->getTMPList();
        return json($res);
    }

    //模版消息
    public function wx_tplmesg()
    {
        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $OpenTemplate = new OpenTemplate();
        $wx_open_id = $Momerchant->where(['id' => $top_mid])->value('wx_open_id');
        $pay['type'] = 'pay_tpl';
        $pay['wx_open_id'] = $wx_open_id;
        $ye['type'] = 'card_ye_tpl';
        $ye['wx_open_id'] = $wx_open_id;
        $zs['type'] = 'card_zs_tpl';
        $zs['wx_open_id'] = $wx_open_id;
        $bb['type'] = 'pre_man_tpl';
        $bb['wx_open_id'] = $wx_open_id;
        $paytpl = $OpenTemplate->where($pay)->find();
        $yetpl = $OpenTemplate->where($ye)->find();
        $zstpl = $OpenTemplate->where($zs)->find();
        $bbtpl = $OpenTemplate->where($bb)->find();
        $momach = $Momerchant->where('id', $top_mid)->find();
        $this->assign('bbtpl', $bbtpl);
        $this->assign('paytpl', $paytpl);
        $this->assign('yetpl', $yetpl);
        $this->assign('zstpl', $zstpl);
        $this->assign('momach', $momach);
        return $this->fetch();

    }

    //设置所属行业
    public function setindustry()
    {
        if (Request()->isAjax()) {
            $industry_id1 = '1';
            $industry_id2 = '2';
            $option = $this->options();
            $wxObj = new Wxobjopen($option);
            $res = $wxObj->setTMIndustry($industry_id1, $industry_id2);
            if (isset($res['primary_industry']) && isset($res['secondary_industry'])) {
                $data['code'] = 0;
                $data['message'] = '设置成功';
            } else {
                $data['code'] = 9002;
                $data['message'] = '设置失败' . $res['errmsg'];
            }
            return json($data);
        }
    }

    //设置
    public function settemlpid()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $OpenTemplate = new OpenTemplate();
            $Momerchant = new Momerchant();
            $top_mid = Session::get('login_top_mid');
            $wx_open_id = $Momerchant->where(['id' => $top_mid])->value('wx_open_id');
            $datas['type'] = $arr['type'];
            $datas['template_id'] = $arr['template_id'];
            $datas['wx_open_id'] = $wx_open_id;
            $datas['addtime'] = time();
            $res = $OpenTemplate->allowField(true)->saveAll($datas);
            if ($res) {
                $this->success('提交设置成功', 'wxsystem/wx_tplmesg');
            } else {
                $this->error('提交设置失败', 'wxsystem/wx_tplmesg');
            }
        }
    }

    //获得模板ID
    public function gettemlpid()
    {
        //return json(request());
        if (request()->isAjax()) {

            $arr = request()->post();
            switch ($arr['type']) {
                //支付
                case 'pay_tpl':
                    $arr['tpl_id'] = 'OPENTM408727351';
                    break;
                //余额
                case 'card_ye_tpl':
                    $arr['tpl_id'] = 'OPENTM401833445';
                    break;
                //赠送
                case 'card_zs_tpl':
                    $arr['tpl_id'] = 'OPENTM200772305';
                    break;
                //报表
                case 'pre_man_tpl':
                    $arr['tpl_id'] = 'OPENTM201041719';
                    break;
            }
            $option = $this->options();
            $wxObj = new Wxobjopen($option);
            $res = $wxObj->addTemplateMessage($arr['tpl_id']);
            //错误提示翻译
            $Helpinfo = new Helpinfo();
            $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
            //END
            if ($res['errcode'] == 0) {
                $OpenTemplate = new OpenTemplate();
                $Momerchant = new Momerchant();
                $top_mid = Session::get('login_top_mid');
                $wx_open_id = $Momerchant->where(['id' => $top_mid])->value('wx_open_id');
                $datas['type'] = $arr['type'];
                $datas['template_id'] = $res['template_id'];
                $datas['wx_open_id'] = $wx_open_id;
                $datas['addtime'] = time();
                $resu = $OpenTemplate->allowField(true)->save($datas);
                if ($resu) {
                    $data['code'] = 0;
                    $data['data'] = $res['template_id'];
                } else {
                    $data['code'] = 9002;
                    $data['message'] = '设置失败-'.$res['errcode'].':' . $errmsg;
                }
            } else {
                $data['code'] = 9001;
                $data['message'] = '设置失败-' .$res['errcode'].':'. $errmsg;
            }
            return json($data);
        }
    }


    //授权信息
    public function wx_authinfo()
    {
        $sarr = Session::get('login_top_mid');
        $Agent = new Momerchant();
        $user = $Agent->where('id', $sarr)->find();

        $wxopen = WxOpen::get($user['wx_open_id']);
        $wxopenxcx = WxOpen::get($user['wx_open_id_xcx']);
        $this->assign('wxopen', $wxopen);
        $this->assign('wxopenxcx', $wxopenxcx);
        $this->assign('user', $user);
        return $this->fetch();
    }

    public function open_auth()
    {
        $request = request();
        $System = new \app\common\model\System();

        $Momerchant = new Momerchant();
        $agent=$Momerchant->where(array('id'=> request()->param('id')))->value('agent');
        $Agent=new Agent();
        $config=$Agent->where(array('id'=>$agent))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
        );
        $weObj = new Wxobjopen($options);
        $pre_auth_code = $weObj->get_pre_auth_code();

        if (!$request->get('auth_code')) {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $callback = $http_type . $_SERVER['HTTP_HOST'] . url("wxsystem/open_auth", $_GET);
            $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $config['component_appid'] . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=" . $callback;
            header("Location: $url");
            exit();
        } else {


            $appinfo = $weObj->authorization_info($request->get('auth_code'));
            $auth_appid = $appinfo['authorization_info']['authorizer_appid'];
            $auther['component_appid'] = $config['component_appid'];
            $auther['authorizer_appid'] = $auth_appid;
            $auther_info = $weObj->get_auther_info($auther);
            if ($request->param('auth_action') == "xcx") {
                if (!isset($auther_info['authorizer_info']['MiniProgramInfo'])){
                    $this->error('请授权类型为微信小程序');
                }
                $data['auth_action'] = 1;
            } else {
                if (isset($auther_info['authorizer_info']['MiniProgramInfo'])){
                    $this->error('请授权类型为微信公众号');
                }
                $data['auth_action'] = 0;
            }
            if ($request->param('auth_action') == "xcx" || ($auther_info['authorizer_info']['service_type_info']['id'] == 2 && ($auther_info['authorizer_info']['verify_type_info']['id'] == 0 || $auther_info['authorizer_info']['verify_type_info']['id'] == 3))) {
                $data['gh_nick_name'] = $auther_info['authorizer_info']['nick_name'];
                $data['service_type_info'] = $auther_info['authorizer_info']['service_type_info']['id'];
                $data['verify_type_info'] = $auther_info['authorizer_info']['verify_type_info']['id'];
                $data['gh_id'] = $auther_info['authorizer_info']['user_name'];
                $data['alias'] = $auther_info['authorizer_info']['alias'];
                $data['qrcode_url'] = $auther_info['authorizer_info']['qrcode_url'];
                $data['principal_name'] = $auther_info['authorizer_info']['principal_name'];
                $data['wx_open_info'] = json_encode($auther_info, JSON_UNESCAPED_UNICODE);
                $data['authorizer_appid'] = $auth_appid;
                $data['authorizer_refresh_token'] = $appinfo['authorization_info']['authorizer_refresh_token'];
                $data['at_access_token'] = $appinfo['authorization_info']['authorizer_access_token'];
                $data['at_addtime'] = time();
                $data['at_expires_in'] = 7000;
                $data['addtime'] = time();
                $data['zt'] = 1;
                $func_info = "";
                foreach ($appinfo['authorization_info']['func_info'] as $k => $v) {
                    $func_info .= $v['funcscope_category']['id'] . ',';
                }
                $WxOpen = new WxOpen();
                $data['func_info'] = $func_info;
                $wx_open = $WxOpen->where(array('authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']))->find();

                if ($wx_open) {
                    $sj = $WxOpen->save($data, ['authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']]);
                    if ($request->param('auth_action') == "xcx") {
                        $da2['wx_open_id_xcx'] = $wx_open['id'];
                    } else {
                        $da2['wx_open_id'] = $wx_open['id'];
                    }
                } else {
                    $sj = $WxOpen->save($data);
                    if ($request->param('auth_action') == "xcx") {
                        $da2['wx_open_id_xcx'] = $WxOpen->id;
                    } else {
                        $da2['wx_open_id'] = $WxOpen->id;
                    }
                }
                $da2['auth_type'] = 1;
                $mss['id'] = request()->param('id');
                $Momerchant = new Momerchant();
                $Momerchant->save($da2, $mss);
                //  end
                $Merchant = new Merchant();
                $mapss['top_mid'] = $mss['id'];
                $da3 = $da2;
                $Merchant->allowField(true)->save($da3,$mapss);

                if ($sj) {
                    $this->success('授权成功', url("wxsystem/wx_authinfo"));
                } else {
                    $this->error('授权失败');
                }
            } else {
                $this->error('该公众号为订阅号或者未通过微信认证，请确认后重新授权');
            }
        }

    }

    //获取公众号二维码
    public function getwxqrcode(){

        $arr = request()->param();
        $Cardmember = new CardMember();
        $Momerchant = new Momerchant();
        $WxOpen = new WxOpen();
        $map['top_mid'] = $Cardmember->where(['card_id'=>$arr['card_id']])->value('top_mid');
        $wx_open_id = $Momerchant->where($map)->value('wx_open_id');
        $qrcode = $WxOpen->where(['id' => $wx_open_id])->value('qrcode');
        if ($qrcode){
            $data['code'] = 0;
            $data['message'] = 0;
            $data['date'] = $qrcode;
        }else{
            $data['code'] = 9001;
            $data['message'] = 0;
            $data['date'] = '';
        }
        return json($data);
    }

    //微信API参数  根据代理商当前登陆账号获取
    public function options()
    {
        Session::set('openid', null);
        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent=new Agent();
        $momerchantinfo=$Momerchant->where('id', $top_mid)->field('wx_open_id,agent')->find();
        $wx_open_id = $momerchantinfo['wx_open_id'];
//        $config = $System->where(['id' => 1])->find();
        $config = $Agent->where(['id' =>$momerchantinfo['agent']])->find();
        $users = $WxOpen->where(['id' => $wx_open_id])->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }



}